import { createClient, SupabaseClient } from '@supabase/supabase-js';
import winston from 'winston';
import fs from 'fs/promises';
import path from 'path';

export interface EmailContent {
  subject: string;
  html: string;
  text: string;
}

export interface TemplateData {
  user?: {
    firstName: string;
    lastName: string;
    email: string;
  };
  papers?: Array<{
    id: string;
    title: string;
    abstract: string;
    authors: string[];
    arxivId: string;
    categories: string[];
    publishedDate: string;
    url: string;
    relevanceScore?: number;
    reason?: string;
  }>;
  summary?: {
    totalPapers: number;
    categoriesCovered: string[];
    timeRange: string;
  };
  preferences?: {
    categories: string[];
    keywords: string[];
    frequency: string;
  };
  unsubscribeUrl?: string;
  trackingPixelUrl?: string;
  baseUrl?: string;
  [key: string]: any;
}

export class EmailTemplate {
  private supabase: SupabaseClient;
  private logger: winston.Logger;
  private templateCache: Map<string, string> = new Map();

  constructor(supabaseUrl: string, supabaseKey: string, logger: winston.Logger) {
    this.supabase = createClient(supabaseUrl, supabaseKey);
    this.logger = logger;
  }

  /**
   * Generate email from template
   */
  async generateEmail(templateType: string, data: TemplateData): Promise<EmailContent> {
    try {
      const template = await this.getTemplate(templateType);
      const compiledTemplate = this.compileTemplate(template, data);
      
      return {
        subject: this.generateSubject(templateType, data),
        html: compiledTemplate.html,
        text: this.htmlToText(compiledTemplate.html)
      };
    } catch (error) {
      this.logger.error(`Failed to generate email template ${templateType}:`, error);
      throw error;
    }
  }

  /**
   * Get template by type
   */
  private async getTemplate(templateType: string): Promise<{ html: string; subject: string }> {
    // Check cache first
    if (this.templateCache.has(templateType)) {
      return JSON.parse(this.templateCache.get(templateType)!);
    }

    // Built-in templates
    const templates = {
      'daily_digest': this.getDailyDigestTemplate(),
      'weekly_summary': this.getWeeklySummaryTemplate(),
      'paper_alert': this.getPaperAlertTemplate(),
      'welcome_series_1': this.getWelcomeSeriesTemplate(1),
      'welcome_series_2': this.getWelcomeSeriesTemplate(2),
      'welcome_series_3': this.getWelcomeSeriesTemplate(3),
      'subscription_confirmation': this.getSubscriptionConfirmationTemplate(),
      'unsubscribe_confirmation': this.getUnsubscribeConfirmationTemplate(),
      'preference_update': this.getPreferenceUpdateTemplate()
    };

    const template = templates[templateType as keyof typeof templates];
    if (!template) {
      throw new Error(`Unknown template type: ${templateType}`);
    }

    // Cache template
    this.templateCache.set(templateType, JSON.stringify(template));
    
    return template;
  }

  /**
   * Compile template with data
   */
  private compileTemplate(template: { html: string; subject: string }, data: TemplateData): { html: string; subject: string } {
    let html = template.html;
    let subject = template.subject;

    // Replace variables in HTML and subject
    const replaceVariables = (text: string): string => {
      return text.replace(/\{\{([^}]+)\}\}/g, (match, key) => {
        const keys = key.trim().split('.');
        let value: any = data;
        
        for (const k of keys) {
          value = value?.[k];
        }
        
        if (value === undefined || value === null) {
          return '';
        }
        
        if (typeof value === 'object') {
          return JSON.stringify(value);
        }
        
        return String(value);
      });
    };

    html = replaceVariables(html);
    subject = replaceVariables(subject);

    return { html, subject };
  }

  /**
   * Generate subject line based on template type and data
   */
  private generateSubject(templateType: string, data: TemplateData): string {
    const subjects = {
      'daily_digest': `📚 Your Daily ArXiv Digest - ${data.summary?.totalPapers || 0} New Papers`,
      'weekly_summary': `📊 Weekly Research Roundup - ${data.summary?.timeRange}`,
      'paper_alert': `🔔 New Paper Alert: ${data.papers?.[0]?.title?.substring(0, 50)}...`,
      'welcome_series_1': `🎉 Welcome to ArXiv Research Hub!`,
      'welcome_series_2': `📖 Discover Your Research Interests`,
      'welcome_series_3': `🚀 Maximize Your Research Efficiency`,
      'subscription_confirmation': `✅ Subscription Confirmed`,
      'unsubscribe_confirmation': `📭 You've been unsubscribed`,
      'preference_update': `⚙️ Email preferences updated`
    };

    return subjects[templateType as keyof typeof subjects] || 'ArXiv Research Hub Update';
  }

  /**
   * Convert HTML to plain text
   */
  private htmlToText(html: string): string {
    return html
      .replace(/<[^>]*>/g, '')
      .replace(/&nbsp;/g, ' ')
      .replace(/&amp;/g, '&')
      .replace(/&lt;/g, '<')
      .replace(/&gt;/g, '>')
      .replace(/&quot;/g, '"')
      .replace(/&#39;/g, "'")
      .replace(/\s+/g, ' ')
      .trim();
  }

  /**
   * Daily digest template
   */
  private getDailyDigestTemplate(): { html: string; subject: string } {
    return {
      html: `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Daily ArXiv Digest</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
        
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f8fafc;
        }
        
        .email-container {
            max-width: 600px;
            margin: 0 auto;
            background: #ffffff;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px 40px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 28px;
            font-weight: 600;
            margin-bottom: 8px;
        }
        
        .header p {
            font-size: 16px;
            opacity: 0.9;
        }
        
        .content {
            padding: 40px;
        }
        
        .greeting {
            font-size: 18px;
            margin-bottom: 30px;
            color: #4a5568;
        }
        
        .summary-box {
            background: #f7fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 30px;
        }
        
        .summary-title {
            font-size: 16px;
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 15px;
        }
        
        .summary-stats {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
        }
        
        .stat-item {
            text-align: center;
        }
        
        .stat-number {
            font-size: 24px;
            font-weight: 700;
            color: #667eea;
            display: block;
        }
        
        .stat-label {
            font-size: 12px;
            color: #718096;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .paper-section {
            margin-bottom: 40px;
        }
        
        .section-title {
            font-size: 20px;
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 20px;
            border-bottom: 2px solid #e2e8f0;
            padding-bottom: 10px;
        }
        
        .paper-card {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            transition: box-shadow 0.2s;
        }
        
        .paper-card:hover {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
        
        .paper-title {
            font-size: 16px;
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 8px;
            line-height: 1.4;
        }
        
        .paper-title a {
            color: #667eea;
            text-decoration: none;
        }
        
        .paper-title a:hover {
            text-decoration: underline;
        }
        
        .paper-authors {
            font-size: 14px;
            color: #718096;
            margin-bottom: 10px;
        }
        
        .paper-abstract {
            font-size: 14px;
            color: #4a5568;
            line-height: 1.5;
            margin-bottom: 15px;
        }
        
        .paper-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 10px;
        }
        
        .paper-categories {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }
        
        .category-tag {
            background: #edf2f7;
            color: #4a5568;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }
        
        .paper-date {
            font-size: 12px;
            color: #a0aec0;
        }
        
        .relevance-score {
            background: linear-gradient(135deg, #48bb78, #38a169);
            color: white;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 600;
        }
        
        .cta-section {
            background: #f7fafc;
            border-radius: 8px;
            padding: 30px;
            text-align: center;
            margin: 40px 0;
        }
        
        .cta-title {
            font-size: 18px;
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 10px;
        }
        
        .cta-button {
            display: inline-block;
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            padding: 12px 30px;
            border-radius: 6px;
            text-decoration: none;
            font-weight: 600;
            margin-top: 15px;
        }
        
        .footer {
            background: #2d3748;
            color: #a0aec0;
            padding: 30px;
            text-align: center;
        }
        
        .footer-links {
            margin-bottom: 20px;
        }
        
        .footer-links a {
            color: #cbd5e0;
            text-decoration: none;
            margin: 0 15px;
            font-size: 14px;
        }
        
        .footer-text {
            font-size: 12px;
            line-height: 1.5;
        }
        
        .unsubscribe {
            margin-top: 15px;
        }
        
        .unsubscribe a {
            color: #a0aec0;
            font-size: 12px;
        }
        
        @media (max-width: 480px) {
            .content { padding: 20px; }
            .header { padding: 20px; }
            .header h1 { font-size: 24px; }
            .summary-stats { flex-direction: column; }
            .paper-meta { flex-direction: column; align-items: flex-start; }
        }
    </style>
</head>
<body>
    <div class="email-container">
        <div class="header">
            <h1>📚 Daily ArXiv Digest</h1>
            <p>Your personalized research updates</p>
        </div>
        
        <div class="content">
            <div class="greeting">
                Hello {{user.firstName}},
            </div>
            
            <div class="summary-box">
                <div class="summary-title">Today's Research Summary</div>
                <div class="summary-stats">
                    <div class="stat-item">
                        <span class="stat-number">{{summary.totalPapers}}</span>
                        <span class="stat-label">New Papers</span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-number">{{summary.categoriesCovered.length}}</span>
                        <span class="stat-label">Categories</span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-number">{{summary.timeRange}}</span>
                        <span class="stat-label">Time Range</span>
                    </div>
                </div>
            </div>
            
            <div class="paper-section">
                <div class="section-title">🔥 Recommended for You</div>
                
                {{#each papers}}
                <div class="paper-card">
                    <div class="paper-title">
                        <a href="{{url}}" target="_blank">{{title}}</a>
                    </div>
                    <div class="paper-authors">{{authors.join ', '}}</div>
                    <div class="paper-abstract">{{abstract}}</div>
                    <div class="paper-meta">
                        <div class="paper-categories">
                            {{#each categories}}
                            <span class="category-tag">{{this}}</span>
                            {{/each}}
                        </div>
                        <div style="display: flex; gap: 10px; align-items: center;">
                            {{#if relevanceScore}}
                            <span class="relevance-score">{{relevanceScore}}% match</span>
                            {{/if}}
                            <span class="paper-date">{{publishedDate}}</span>
                        </div>
                    </div>
                </div>
                {{/each}}
            </div>
            
            <div class="cta-section">
                <div class="cta-title">Discover More Research</div>
                <p>Explore our full collection of papers and customize your preferences.</p>
                <a href="{{baseUrl}}/dashboard" class="cta-button">Visit Dashboard</a>
            </div>
        </div>
        
        <div class="footer">
            <div class="footer-links">
                <a href="{{baseUrl}}/preferences">Preferences</a>
                <a href="{{baseUrl}}/dashboard">Dashboard</a>
                <a href="{{baseUrl}}/support">Support</a>
            </div>
            <div class="footer-text">
                You're receiving this because you subscribed to ArXiv Research Hub.<br>
                ArXiv Research Hub - Advancing Scientific Discovery
            </div>
            <div class="unsubscribe">
                <a href="{{unsubscribeUrl}}">Unsubscribe</a> | 
                <a href="{{baseUrl}}/preferences">Update Preferences</a>
            </div>
        </div>
    </div>
    
    <!-- Tracking Pixel -->
    {{#if trackingPixelUrl}}
    <img src="{{trackingPixelUrl}}" width="1" height="1" style="display:none;" alt="">
    {{/if}}
</body>
</html>`,
      subject: `📚 Your Daily ArXiv Digest - {{summary.totalPapers}} New Papers`
    };
  }

  /**
   * Weekly summary template
   */
  private getWeeklySummaryTemplate(): { html: string; subject: string } {
    return {
      html: `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Weekly Research Summary</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
        
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f8fafc;
        }
        
        .email-container {
            max-width: 600px;
            margin: 0 auto;
            background: #ffffff;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .header {
            background: linear-gradient(135deg, #3182ce 0%, #2b6cb0 100%);
            color: white;
            padding: 40px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 32px;
            font-weight: 700;
            margin-bottom: 10px;
        }
        
        .header p {
            font-size: 18px;
            opacity: 0.9;
        }
        
        .content {
            padding: 40px;
        }
        
        .insights-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 40px;
        }
        
        .insight-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 25px;
            border-radius: 12px;
            text-align: center;
        }
        
        .insight-number {
            font-size: 36px;
            font-weight: 700;
            display: block;
            margin-bottom: 8px;
        }
        
        .insight-label {
            font-size: 14px;
            opacity: 0.9;
        }
        
        .trending-section {
            background: #f7fafc;
            border-radius: 12px;
            padding: 30px;
            margin-bottom: 30px;
        }
        
        .trending-title {
            font-size: 22px;
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 20px;
        }
        
        .trending-item {
            display: flex;
            align-items: center;
            padding: 15px 0;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .trending-item:last-child {
            border-bottom: none;
        }
        
        .trending-rank {
            font-size: 18px;
            font-weight: 700;
            color: #667eea;
            min-width: 30px;
        }
        
        .trending-content {
            margin-left: 20px;
        }
        
        .trending-paper {
            font-size: 16px;
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 5px;
        }
        
        .trending-stats {
            font-size: 14px;
            color: #718096;
        }
        
        @media (max-width: 480px) {
            .content { padding: 20px; }
            .header { padding: 30px 20px; }
            .insights-grid { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>
    <div class="email-container">
        <div class="header">
            <h1>📊 Weekly Roundup</h1>
            <p>{{summary.timeRange}}</p>
        </div>
        
        <div class="content">
            <div class="insights-grid">
                <div class="insight-card">
                    <span class="insight-number">{{summary.totalPapers}}</span>
                    <span class="insight-label">Papers This Week</span>
                </div>
                <div class="insight-card">
                    <span class="insight-number">{{summary.categoriesCovered.length}}</span>
                    <span class="insight-label">Research Areas</span>
                </div>
            </div>
            
            <div class="trending-section">
                <div class="trending-title">🔥 Trending This Week</div>
                {{#each papers}}
                <div class="trending-item">
                    <div class="trending-rank">{{@index + 1}}</div>
                    <div class="trending-content">
                        <div class="trending-paper">{{title}}</div>
                        <div class="trending-stats">{{authors.0}} et al. • {{categories.0}}</div>
                    </div>
                </div>
                {{/each}}
            </div>
        </div>
        
        <div class="footer">
            <div class="footer-links">
                <a href="{{baseUrl}}/preferences">Preferences</a>
                <a href="{{baseUrl}}/dashboard">Dashboard</a>
            </div>
            <div class="unsubscribe">
                <a href="{{unsubscribeUrl}}">Unsubscribe</a>
            </div>
        </div>
    </div>
</body>
</html>`,
      subject: `📊 Weekly Research Roundup - {{summary.timeRange}}`
    };
  }

  /**
   * Paper alert template
   */
  private getPaperAlertTemplate(): { html: string; subject: string } {
    return {
      html: `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Paper Alert</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
        
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f8fafc;
        }
        
        .email-container {
            max-width: 600px;
            margin: 0 auto;
            background: #ffffff;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .header {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .alert-icon {
            font-size: 48px;
            margin-bottom: 10px;
        }
        
        .alert-title {
            font-size: 24px;
            font-weight: 600;
        }
        
        .content {
            padding: 40px;
        }
        
        .paper-highlight {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 12px;
            margin-bottom: 30px;
        }
        
        .paper-title {
            font-size: 20px;
            font-weight: 600;
            margin-bottom: 15px;
            line-height: 1.4;
        }
        
        .paper-authors {
            font-size: 16px;
            opacity: 0.9;
            margin-bottom: 20px;
        }
        
        .quick-actions {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
        }
        
        .action-button {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            padding: 10px 20px;
            border-radius: 6px;
            text-decoration: none;
            font-weight: 500;
            border: 1px solid rgba(255, 255, 255, 0.3);
        }
        
        .action-button:hover {
            background: rgba(255, 255, 255, 0.3);
        }
        
        .paper-details {
            background: #f7fafc;
            padding: 25px;
            border-radius: 8px;
        }
        
        .detail-row {
            display: flex;
            padding: 10px 0;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .detail-row:last-child {
            border-bottom: none;
        }
        
        .detail-label {
            font-weight: 600;
            color: #4a5568;
            min-width: 120px;
        }
        
        .detail-value {
            color: #2d3748;
            flex: 1;
        }
        
        @media (max-width: 480px) {
            .content { padding: 20px; }
            .quick-actions { flex-direction: column; }
        }
    </style>
</head>
<body>
    <div class="email-container">
        <div class="header">
            <div class="alert-icon">🔔</div>
            <div class="alert-title">New Paper Alert</div>
        </div>
        
        <div class="content">
            {{#with papers.0}}
            <div class="paper-highlight">
                <div class="paper-title">{{title}}</div>
                <div class="paper-authors">{{authors.join ', '}}</div>
                <div class="quick-actions">
                    <a href="{{url}}" class="action-button">Read Paper</a>
                    <a href="{{../baseUrl}}/bookmark/{{id}}" class="action-button">Bookmark</a>
                    <a href="{{../baseUrl}}/share/{{id}}" class="action-button">Share</a>
                </div>
            </div>
            
            <div class="paper-details">
                <div class="detail-row">
                    <div class="detail-label">ArXiv ID:</div>
                    <div class="detail-value">{{arxivId}}</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Categories:</div>
                    <div class="detail-value">{{categories.join ', '}}</div>
                </div>
                <div class="detail-row">
                    <div class="detail-label">Published:</div>
                    <div class="detail-value">{{publishedDate}}</div>
                </div>
                {{#if reason}}
                <div class="detail-row">
                    <div class="detail-label">Why this matches:</div>
                    <div class="detail-value">{{reason}}</div>
                </div>
                {{/if}}
            </div>
            {{/with}}
        </div>
        
        <div class="footer">
            <div class="footer-links">
                <a href="{{baseUrl}}/preferences">Update Alert Preferences</a>
            </div>
            <div class="unsubscribe">
                <a href="{{unsubscribeUrl}}">Unsubscribe from alerts</a>
            </div>
        </div>
    </div>
</body>
</html>`,
      subject: `🔔 New Paper Alert: {{papers.0.title}}`
    };
  }

  /**
   * Welcome series templates
   */
  private getWelcomeSeriesTemplate(step: number): { html: string; subject: string } {
    const templates = {
      1: {
        html: `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Welcome to ArXiv Research Hub</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
        
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f8fafc;
        }
        
        .email-container {
            max-width: 600px;
            margin: 0 auto;
            background: #ffffff;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 50px 40px;
            text-align: center;
        }
        
        .welcome-icon {
            font-size: 64px;
            margin-bottom: 20px;
        }
        
        .welcome-title {
            font-size: 28px;
            font-weight: 700;
            margin-bottom: 10px;
        }
        
        .welcome-subtitle {
            font-size: 18px;
            opacity: 0.9;
        }
        
        .content {
            padding: 50px 40px;
            text-align: center;
        }
        
        .welcome-message {
            font-size: 18px;
            color: #4a5568;
            margin-bottom: 30px;
            line-height: 1.7;
        }
        
        .features-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 30px;
            margin: 40px 0;
        }
        
        .feature-item {
            text-align: center;
            padding: 20px;
        }
        
        .feature-icon {
            font-size: 48px;
            margin-bottom: 15px;
        }
        
        .feature-title {
            font-size: 16px;
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 10px;
        }
        
        .feature-description {
            font-size: 14px;
            color: #718096;
            line-height: 1.5;
        }
        
        .cta-button {
            display: inline-block;
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            padding: 15px 40px;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 600;
            font-size: 16px;
            margin: 30px 0;
        }
        
        @media (max-width: 480px) {
            .content, .header { padding: 30px 20px; }
            .features-grid { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>
    <div class="email-container">
        <div class="header">
            <div class="welcome-icon">🎉</div>
            <div class="welcome-title">Welcome to ArXiv Research Hub!</div>
            <div class="welcome-subtitle">Your gateway to cutting-edge research</div>
        </div>
        
        <div class="content">
            <div class="welcome-message">
                Hi {{user.firstName}},<br><br>
                
                Welcome to the future of research discovery! We're thrilled to have you join our community of researchers, academics, and curious minds who are passionate about staying at the forefront of scientific advancement.
            </div>
            
            <div class="features-grid">
                <div class="feature-item">
                    <div class="feature-icon">📚</div>
                    <div class="feature-title">Personalized Digests</div>
                    <div class="feature-description">Get daily summaries of papers tailored to your research interests</div>
                </div>
                <div class="feature-item">
                    <div class="feature-icon">🔔</div>
                    <div class="feature-title">Smart Alerts</div>
                    <div class="feature-description">Never miss important papers from your favorite authors or topics</div>
                </div>
                <div class="feature-item">
                    <div class="feature-icon">📊</div>
                    <div class="feature-title">Research Analytics</div>
                    <div class="feature-description">Track trends and discover emerging fields in your area of study</div>
                </div>
            </div>
            
            <a href="{{baseUrl}}/onboarding" class="cta-button">Complete Your Setup</a>
            
            <p style="margin-top: 30px; font-size: 14px; color: #718096;">
                Over the next few days, we'll send you helpful tips to make the most of your ArXiv Research Hub experience.
            </p>
        </div>
        
        <div class="footer">
            <div class="footer-text">
                Questions? Reply to this email - we'd love to help!
            </div>
        </div>
    </div>
</body>
</html>`,
        subject: `🎉 Welcome to ArXiv Research Hub!`
      },
      2: {
        html: `<!-- Welcome Series Step 2 Template -->`,
        subject: `📖 Discover Your Research Interests`
      },
      3: {
        html: `<!-- Welcome Series Step 3 Template -->`,
        subject: `🚀 Maximize Your Research Efficiency`
      }
    };

    return templates[step as keyof typeof templates] || templates[1];
  }

  /**
   * Subscription confirmation template
   */
  private getSubscriptionConfirmationTemplate(): { html: string; subject: string } {
    return {
      html: `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Subscription Confirmed</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
        
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f8fafc;
        }
        
        .email-container {
            max-width: 600px;
            margin: 0 auto;
            background: #ffffff;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .header {
            background: linear-gradient(135deg, #48bb78 0%, #38a169 100%);
            color: white;
            padding: 40px;
            text-align: center;
        }
        
        .success-icon {
            font-size: 64px;
            margin-bottom: 20px;
        }
        
        .header h1 {
            font-size: 28px;
            font-weight: 600;
        }
        
        .content {
            padding: 40px;
            text-align: center;
        }
        
        .confirmation-message {
            font-size: 18px;
            color: #4a5568;
            margin-bottom: 30px;
        }
        
        .next-steps {
            background: #f7fafc;
            padding: 30px;
            border-radius: 8px;
            text-align: left;
            margin: 30px 0;
        }
        
        .next-steps h3 {
            font-size: 18px;
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 15px;
        }
        
        .step-list {
            list-style: none;
            padding: 0;
        }
        
        .step-item {
            display: flex;
            align-items: flex-start;
            margin-bottom: 15px;
            padding-left: 30px;
            position: relative;
        }
        
        .step-number {
            position: absolute;
            left: 0;
            top: 0;
            background: #667eea;
            color: white;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: 600;
        }
        
        .step-text {
            color: #4a5568;
        }
        
        @media (max-width: 480px) {
            .content, .header { padding: 30px 20px; }
        }
    </style>
</head>
<body>
    <div class="email-container">
        <div class="header">
            <div class="success-icon">✅</div>
            <h1>Subscription Confirmed!</h1>
        </div>
        
        <div class="content">
            <div class="confirmation-message">
                Great! You'll now receive {{preferences.frequency}} emails with the latest papers in your areas of interest.
            </div>
            
            <div class="next-steps">
                <h3>What happens next?</h3>
                <ul class="step-list">
                    <li class="step-item">
                        <span class="step-number">1</span>
                        <span class="step-text">You'll receive your first digest within 24 hours</span>
                    </li>
                    <li class="step-item">
                        <span class="step-number">2</span>
                        <span class="step-text">Each email will be personalized based on your interests</span>
                    </li>
                    <li class="step-item">
                        <span class="step-number">3</span>
                        <span class="step-text">You can update preferences anytime from your dashboard</span>
                    </li>
                </ul>
            </div>
        </div>
        
        <div class="footer">
            <div class="footer-links">
                <a href="{{baseUrl}}/dashboard">Go to Dashboard</a>
                <a href="{{baseUrl}}/preferences">Update Preferences</a>
            </div>
        </div>
    </div>
</body>
</html>`,
      subject: `✅ Subscription Confirmed`
    };
  }

  /**
   * Unsubscribe confirmation template
   */
  private getUnsubscribeConfirmationTemplate(): { html: string; subject: string } {
    return {
      html: `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Unsubscribed</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
        
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f8fafc;
        }
        
        .email-container {
            max-width: 600px;
            margin: 0 auto;
            background: #ffffff;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .header {
            background: #718096;
            color: white;
            padding: 40px;
            text-align: center;
        }
        
        .content {
            padding: 40px;
            text-align: center;
        }
        
        .resubscribe-link {
            display: inline-block;
            background: #667eea;
            color: white;
            padding: 12px 25px;
            border-radius: 6px;
            text-decoration: none;
            font-weight: 600;
            margin-top: 20px;
        }
        
        @media (max-width: 480px) {
            .content, .header { padding: 30px 20px; }
        }
    </style>
</head>
<body>
    <div class="email-container">
        <div class="header">
            <h1>You've Been Unsubscribed</h1>
        </div>
        
        <div class="content">
            <p>We're sorry to see you go! You will no longer receive email updates from ArXiv Research Hub.</p>
            
            <p style="margin: 20px 0;">
                If you change your mind, you can resubscribe at any time.
            </p>
            
            <a href="{{baseUrl}}/resubscribe?token={{resubscribeToken}}" class="resubscribe-link">
                Resubscribe
            </a>
            
            <p style="margin-top: 30px; font-size: 14px; color: #718096;">
                We'd love to know how we can improve. Feel free to reply to this email with feedback.
            </p>
        </div>
    </div>
</body>
</html>`,
      subject: `📭 You've been unsubscribed`
    };
  }

  /**
   * Preference update template
   */
  private getPreferenceUpdateTemplate(): { html: string; subject: string } {
    return {
      html: `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Preferences Updated</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
        
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f8fafc;
        }
        
        .email-container {
            max-width: 600px;
            margin: 0 auto;
            background: #ffffff;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .header {
            background: linear-gradient(135deg, #805ad5 0%, #6b46c1 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .content {
            padding: 40px;
        }
        
        .preference-summary {
            background: #f7fafc;
            padding: 25px;
            border-radius: 8px;
            margin: 20px 0;
        }
        
        .preference-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 0;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .preference-item:last-child {
            border-bottom: none;
        }
        
        .preference-label {
            font-weight: 600;
            color: #4a5568;
        }
        
        .preference-value {
            color: #2d3748;
        }
        
        @media (max-width: 480px) {
            .content, .header { padding: 20px; }
        }
    </style>
</head>
<body>
    <div class="email-container">
        <div class="header">
            <h1>⚙️ Preferences Updated</h1>
        </div>
        
        <div class="content">
            <p>Hi {{user.firstName}},</p>
            
            <p style="margin: 20px 0;">
                Your email preferences have been successfully updated. Here's a summary of your current settings:
            </p>
            
            <div class="preference-summary">
                <div class="preference-item">
                    <span class="preference-label">Email Frequency:</span>
                    <span class="preference-value">{{preferences.frequency}}</span>
                </div>
                <div class="preference-item">
                    <span class="preference-label">Research Categories:</span>
                    <span class="preference-value">{{preferences.categories.join ', '}}</span>
                </div>
                <div class="preference-item">
                    <span class="preference-label">Keywords:</span>
                    <span class="preference-value">{{preferences.keywords.join ', '}}</span>
                </div>
            </div>
            
            <p style="margin-top: 30px;">
                Your next email will reflect these changes. You can update your preferences anytime from your dashboard.
            </p>
        </div>
        
        <div class="footer">
            <div class="footer-links">
                <a href="{{baseUrl}}/preferences">Update Preferences</a>
                <a href="{{baseUrl}}/dashboard">Dashboard</a>
            </div>
        </div>
    </div>
</body>
</html>`,
      subject: `⚙️ Email preferences updated`
    };
  }
}